package com.ys.config;

import com.ys.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName JWTInterceptor
 * @Author 1628994918qq.com
 * @Date 2023/2/28 20:51
 *
 * JWT拦截器
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private JWTUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取Url
        /*String url = request.getRequestURI();
        //如果包含login，则直接去验证用户ID密码。不需要去验证token，可以利用这里设置白名单
        if (url.startsWith("login") ||url.startsWith("/html") || url.startsWith("/js") || url.contains("/favicon.ico")){
            return true;
        }*/
        //验证token是否为空
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        if (null == token || token.isEmpty()) {
            return false;
        }
        //解析token
        Claims claims = jwtUtils.parseJWT(token);
        String stuId = claims.get("stuId", String.class);
        request.setAttribute("stuId",stuId);
        return true;
    }
}
